<!--
 * @description  : 查看真烟流动
 * @descriptionDetail: 查看真烟流动
 * @copyright    : 浙江烟草
 * @author       : lcm
 * @create       : 2022-09-27 09:58:58
-->
<template>
  <view>
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="title"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="nav-right-icon" style="display: inline-flex;">
        <view @tap="handlerReload">
          刷新
        </view>
        <view @tap="handlerShowSearch" style="margin-left: 10px;">
          筛选
        </view>
      </view>
    </theme-navbar>
    <!-- #endif -->
    <view style="padding-bottom:55px">
      <swiper-list
        :headers="swiperCfg[hIndex].headers"
        :dataSource="swiperCfg[hIndex].dataSource"
        :keyCode="swiperCfg[hIndex].key"
        :key="nowKey"
        :flag="chFlag"
        :previewOrgUuid="previewOrgUuid"
        :orgLevel="orgLevel"
        :areaSwiperIdx="areaSwiperIdx"
        :unitName="unitName"
        :searchParam="searchParam"
        @click-item="handleClickRow"
        @preview="handlePreview"
        @resetTitle="handleResetTitle"
      ></swiper-list>
      <view class="notes">
        注：该模块需获取卷烟码段信息,故仅统计已上报案件
      </view>

		<!-- #ifdef H5-DINGDING || H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    </view>
    <view>
      <u-popup mode="top" border-radius="30" :height="tabIndex==2 ? '60%' : '80%'" v-model="showSearch">
        <view style="width:100%;height:20px;background-color:#e0f2ff;color:#72bff6;font-size:16px;">
          数据截至日期：{{ formData.headerDateEnd }}
        </view>
        <u-card
          margin="10rpx"
          :foot-border-top="false"
          :head-border-bottom="false"
          :show-head="false"
        >
          <template #body>
            <u-row gutter="16">
              <u-col span="4">
                <u-icon name="calendar" size="32" label="时间选择"></u-icon>
              </u-col>
              <u-col span="4" v-for="(item, idx) in timeSelect" :key="idx">
                <u-tag
                  class="tagsize"
                  type="primary"
                  :text="item.text"
                  :mode="formData.cigTime == item.value ? 'dark' : 'plain'"
                  @click="onClick(item.value)"
                >
                </u-tag>
              </u-col>
            </u-row>
            <u-row gutter="16" style="margin-top:8px;">
              <u-col span="4.5" text-align="center">
                <z-date placeholder="请选择" format="yyyy-MM-dd" v-model="formData.dateStart" />
              </u-col>
              <u-col span="3" text-align="center">
                至
              </u-col>
              <u-col span="4.5" text-align="center">
                <z-date placeholder="请选择" format="yyyy-MM-dd" v-model="formData.dateEnd" />
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-card
          margin="10rpx"
          :foot-border-top="false"
          :head-border-bottom="false"
          :show-head="false"
          box-shadow="#e5e5e5 0px 0px 50px"
        >
          <template #body>
            <u-row gutter="16">
              <u-col span="4">
                <u-icon name="minus-circle" size="32" label="卷烟单位"></u-icon>
              </u-col>
              <u-col span="4" v-for="(item, idx) in cigUnitSelect" :key="idx">
                <u-tag
                  class="tagsize"
                  type="primary"
                  :text="item.text"
                  :mode="formData.cigaUnit == item.value ? 'dark' : 'plain'"
                  @click="changeUnit(item)"
                >
                </u-tag>
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-card
          margin="10rpx"
          :bodyStyle="bodyStyle"
          :foot-border-top="false"
          :head-border-bottom="false"
          box-shadow="#e5e5e5 0px 0px 50px"
          v-if="tabIndex==0"
        >
          <template #head>
            <u-row gutter="16">
              <u-col span="9">
                <u-icon name="minus-circle" size="32" label="案件分类(万支)"></u-icon>
              </u-col>
            </u-row>
          </template>
          <template #body>
            <u-row gutter="16">
              <u-col span="3" v-for="(item, idx) in cigTypeSelect" :key="idx">
                <u-tag
                  class="tagsize"
                  style="margin-bottom:5px"
                  dictType="I_TRACK_CASE_TYPE"
                  type="primary"
                  :text="item.bcbName.replace('万元','')"
                  size="default"
                  :mode="formData.cigKind == item.bcbCode ? 'dark' : 'plain'"
                  @click="formData.cigKind = item.bcbCode"
                >
                </u-tag>
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-card
          margin="10rpx"
          :bodyStyle="bodyStyle"
          :foot-border-top="false"
          :head-border-bottom="false"
          box-shadow="#e5e5e5 0px 0px 50px"
          v-if="tabIndex==0"
        >
          <template #head>
            <u-row gutter="16">
              <u-col span="9">
                <u-icon name="minus-circle" size="32" label="案值分类(万元)"></u-icon>
              </u-col>
            </u-row>
          </template>
          <template #body>
            <u-row gutter="16">
              <u-col span="3" v-for="(item, idx) in cigValueSelect" :key="idx">
                <u-tag
                  class="tagsize"
                  style="margin-bottom:5px"
                  dictType="I_TRACK_CASE_TYPE"
                  type="primary"
                  :text="item.bcbName.replace('万元','')"
                  size="default"
                  :mode="formData.cigValue == item.bcbCode ? 'dark' : 'plain'"
                  @click="formData.cigValue = item.bcbCode"
                >
                </u-tag>
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-card
          margin="10rpx"
          :bodyStyle="bodyStyle"
          :foot-border-top="false"
          :head-border-bottom="false"
          box-shadow="#e5e5e5 0px 0px 50px"
          v-if="tabIndex==1"
        >
          <template #head>
            <u-row gutter="16">
              <u-col span="4">
                <u-icon name="minus-circle" size="32" label="显示数量"></u-icon>
              </u-col>
            </u-row>
          </template>
          <template #body>
            <u-row gutter="16">
              <u-col span="12" style="display: inline-flex;">
                展示前<u-input type="number" style="text-align: center;font-weight:600;" placeholder="最大输入1000" v-model="formData.cigaRank" />位卷烟
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-card
          margin="10rpx"
          :foot-border-top="false"
          :head-border-bottom="false"
          box-shadow="#e5e5e5 0px 0px 50px"
          v-if="tabIndex==1"
        >
          <template #head>
            <u-row gutter="16">
              <u-col span="9">
                <u-icon name="minus-circle" size="32" label="卷烟品规"></u-icon>
              </u-col>
            </u-row>
          </template>
          <template #body>
            <u-row gutter="16">
              <u-col span="12">
                <u-input type="text" placeholder="请输入卷烟品规" v-model="formData.brandName" />
              </u-col>
            </u-row>
          </template>
        </u-card>
        <u-row gutter="16">
          <u-col span="6" text-align="center" style="margin-top:10px">
            <u-button size="medium" @tap="resetSearchParam">
              全部重置
            </u-button>
          </u-col>
          <u-col span="6" text-align="center" style="margin-top:10px">
            <u-button type="primary" size="medium" @tap="handleSearch">
              确定
            </u-button>
          </u-col>
        </u-row>
      </u-popup>
    </view>
    <view class="end">
      <u-tabbar style="height:50px !important;" :list="list" bg-color="#ecf0f1" v-model="tabIndex" :beforeSwitch="handleChangeTab"></u-tabbar>
    </view>
  </view>
</template>
<script>
	import internalService from '@/service/internal/internal.service';
	import {
		ZDate,
	} from '@/components';
	import {
		SwiperList,
	} from './components';
	import {
		dateUtils,
	} from '@/common/util.js';
	import Headers from './realCigFlowSlideHeader';
	import fabButton from '@/components/uni-fab.vue';
	let date = new Date();
	export default {
		components: {
			ZDate,
			SwiperList,
			fabButton,
		},
		data() {
			let userInfo = this.$storage.get(this.$rp.common.USER);
			return {
				userInfo: userInfo,
				orgLevel: userInfo.orgLevel,
				showCity: '',
				unitName: '万支',
				bodyStyle: {
					padding: '0px 15px',
				},
				title: '真烟流动',
				labelWidth: 180,
				showSearch: false,
				chFlag: 0, // 查获0,被查获1
				list: [{
						iconPath: '../../../static/storage/icon_qy.png',
						selectedIconPath: '../../../static/storage/icon_qyb.png',
						text: '区域',
					},
					{
						iconPath: '../../../static/storage/icon_pg.png',
						selectedIconPath: '../../../static/storage/icon_pgb.png',
						text: '品规',
					},
					{
						iconPath: '../../../static/storage/icon_ly.png',
						selectedIconPath: '../../../static/storage/icon_lyb.png',
						text: '来源地',
					},
				],
				tabIndex: 0,
				formData: {
					dateStart: new Date().getFullYear() + '-01-01',
					dateEnd: dateUtils.dateFormat('yyyy-MM-dd', new Date(new Date().getTime() - 24 * 60 * 60 * 1000)),
					newYearStart: new Date().getFullYear() + '-01-01',
					newYearEnd: dateUtils.dateFormat('yyyy-MM-dd', new Date(new Date().getTime() - 24 * 60 * 60 * 1000)),
					newMonthStart: dateUtils.dateFormat('yyyy-MM', new Date()) + '-01',
					headerDateEnd: dateUtils.dateFormat('yyyy-MM-dd', new Date(new Date().getTime() - 24 * 60 * 60 * 1000)),
					cigTime: '0',
					cigaUnit: '2', // 单位
					cigKind: '', //  案件分类（万支）
					cigValue: '', // 案值分类（万元）
					cigaRank: 20, // 展示的品规数量
					brandName: '', // 卷烟品规
					cigaOutFlowType: '',
				},
				cloneFormData: {}, // 克隆一份查询条件数据用于重置
				cigUnitSelect: [{
						text: '条',
						value: '1',
					},
					{
						text: '万支',
						value: '2',
					},
				],
				timeSelect: [{
						text: '当年',
						value: '0',
					},
					{
						text: '当月',
						value: '1',
					},
				],
				cigTypeSelect: this.$u.dic.getByDictCode('I_TRACK_CASE_TYPE'),
				cigValueSelect: this.$u.dic.getByDictCode('I_TRACK_CASE_TYPE'),
				nowKey: 0, // 加这个值用于组件刷新
				areaSwiperOrgUuid: '', // 区域部分点击的专卖局uuid
				hIndex: 0, // 当前显示的列表序号，区域查获、区域被查获、品规、来源地
				previewOrgUuid: '', // 预览的专卖局
				swiperCfg: [
					// swiper分屏配置
					{
						label: '查获卷烟',
						key: 'orgUuid', // 标记唯一主键
						headers: Headers.area,
						dataSource: [],
					},
					{
						label: '被查获卷烟',
						key: 'orgUuid', // 标记唯一主键
						headers: Headers.areaBCH,
						dataSource: [],
					},
					{
						label: '品规',
						key: 'cigaCode',
						headers: Headers.brand,
						dataSource: [],
					},
					{
						label: '来源地',
						key: 'admdiv',
						headers: Headers.source,
						dataSource: [],
					},
				],
				searchParam: {}, // 查询条件
				areaSwiperIdx: 0, // 区域滑屏对应的来源地去向地数据展示（详见swiper-list组件）
				fContent: [{
						iconPath: require('@/static/refresh.png'),
						selectedIconPath: require('@/static/refresh.png'),
						text: '刷新',
						active: false,
					},
					{
						iconPath: require('@/static/sou.png'),
						selectedIconPath: require('@/static/sou.png'),
						text: '筛选',
						active: false,
					},
				],
			};
		},

		watch: {
			title(v) {
				// 调用钉钉标题接口，动态设置展示标题
				this.$deviceApi.setTitle && this.$deviceApi.setTitle(v);
			},
		},
		created() {
			this.chFlag = parseInt(this.$route.query.seizedVal);
			this.handleResetTitle(['查获卷烟', '被查获卷烟', ][this.chFlag]);
			this.hIndex = this.chFlag;
			this.list[2].text = ['来源地', '去向地', ][this.chFlag];
			this.formData.cigaOutFlowType = !this.chFlag ? '01' : '02';
			this.userInfoUuid = this.userInfo.townOrgUuid || this.userInfo.cityOrgUuid || this.userInfo.provOrgUuid;
			this.headers = this.swiperCfg[this.hIndex].headers;
			this.lodingQy(this.chFlag);
			this.cloneFormData = this.$u.deepClone(this.formData);
			console.log(this.orgLevel);
		},

		methods: {
			// 钉钉上设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				// 先放开右侧标题
				this.$deviceApi.setRight('', () => {}, true, true);
				// 设置右侧多按钮，苹果手机对此接口的格式要求比较严格，不能出现多余的符号
				let menuItemStr = '[{"id":"1","text":"刷新"}, {"id":"2","text":"筛选"}]';
				this.$deviceApi.setMenu(JSON.parse(menuItemStr), (res) => {
					if (res.id == 1) {
						this.handlerReload();
					} else if (res.id == 2) {
						this.handlerShowSearch();
					}
				});
				// #endif
			},
			// 重置title
			handleResetTitle(newTitle, swiperIdx) {
				this.areaSwiperIdx = typeof swiperIdx === 'undefined' ? this.areaSwiperIdx : swiperIdx;
				// this.title = newTitle + "(" + this.unitName + ")";
				// 不再显示单位
				this.title = newTitle;
				// 设置钉钉标题
				this.$deviceApi.setTitle && this.$deviceApi.setTitle(this.title);
			},
			// 区域
			lodingQy(chIdx) {
				this.nowKey = new Date().getTime();
				this.hIndex = chIdx || 0;
				this.swiperCfg[this.hIndex].dataSource = [];
				// this.swiperCfg[this.hIndex].headers = this.swiperCfg[this.hIndex].headers.map((h, idx) => {
				//   idx === 0 && h.label.forEach(hd => {
				//     hd.label = hd.orignalLabel + "(" + this.unitName + ")";
				//   });
				//   return Object.assign({}, h, {selectedIdx: chIdx,})
				// });
				let paras = {
					orgUuid: this.previewOrgUuid ||
						(this.$storage.get(this.$rp.common.USER).user.org.benji ?
							this.$storage.get(this.$rp.common.USER).user.org.parentOrgUuid :
							this.$storage.get(this.$rp.common.USER).user.org.orgUuid),
					caseDateBegin: this.formData.dateStart,
					caseDateEnd: this.formData.dateEnd,
					yearDateEnd: (date.getFullYear() - 1).toString() + this.formData.dateEnd.substring(4, 10),
					yearDateStart: (date.getFullYear() - 1).toString() + this.formData.dateStart.substring(4, 10),
					cigaUnit: this.formData.cigaUnit,
					cigaOutFlowType: this.formData.cigaOutFlowType,
					caseCigaQtyType: this.formData.cigKind,
					caseValueType: this.formData.cigValue,
					cigaCode: this.searchParam.cigaCode, // 品规编码
				};
				this.$u.loading('数据加载中...');
				internalService[!chIdx ? 'selectTrueCaseAreaList' : 'selectTrueCaseAreaOutList'](1, 30, paras).then((dr) => {
					this.$u.hideLoading();
					if (dr.success) {
						this.swiperCfg[this.hIndex].dataSource = dr.data;
					} else {
						this.$u.error(dr.msg);
					}
				});
			},
			// 品规列表数据
			lodingBrand(chIdx) {
				this.nowKey = new Date().getTime();
				this.hIndex = 2;
				this.swiperCfg[this.hIndex].dataSource = [];
				let paras = {
					orgUuid: this.areaSwiperOrgUuid ||
						(this.$storage.get(this.$rp.common.USER).user.org.benji ?
							this.$storage.get(this.$rp.common.USER).user.org.parentOrgUuid :
							this.$storage.get(this.$rp.common.USER).user.org.orgUuid),
					caseDateBegin: this.formData.dateStart,
					caseDateEnd: this.formData.dateEnd,
					yearDateEnd: (date.getFullYear() - 1).toString() + this.formData.dateEnd.substring(4, 10),
					yearDateStart: (date.getFullYear() - 1).toString() + this.formData.dateStart.substring(4, 10),
					cigaUnit: this.formData.cigaUnit,
					cigaRank: parseInt(this.formData.cigaRank),
					brandName: this.formData.brandName,
				};
				this.$u.loading('数据加载中...');
				internalService[!chIdx ? 'selectTrueCaseCigaList' : 'selectTrueCaseCigaOutList'](1, 20, paras).then((dr) => {
					this.$u.hideLoading();
					if (dr.success) {
						this.swiperCfg[this.hIndex].dataSource = dr.data;
					} else {
						this.$u.error(dr.msg);
					}
				});
			},
			// 来源地数据
			lodingSource(chIdx) {
				this.nowKey = new Date().getTime();
				this.hIndex = 3;
				this.swiperCfg[this.hIndex].dataSource = [];
				this.swiperCfg[this.hIndex].headers = Headers[['source', 'sourceTo', ][this.chFlag]];
				let paras = {
					orgUuid: this.areaSwiperOrgUuid ||
						(this.$storage.get(this.$rp.common.USER).user.org.benji ?
							this.$storage.get(this.$rp.common.USER).user.org.parentOrgUuid :
							this.$storage.get(this.$rp.common.USER).user.org.orgUuid),
					caseDateBegin: this.formData.dateStart,
					caseDateEnd: this.formData.dateEnd,
					yearDateEnd: (date.getFullYear() - 1).toString() + this.formData.dateEnd.substring(4, 10),
					yearDateStart: (date.getFullYear() - 1).toString() + this.formData.dateStart.substring(4, 10),
					cigaUnit: this.formData.cigaUnit,
					...this.searchParam, // 品规编码等
				};
				// 取消区域选中项会导致orgUuid为空，加一下默认值
				!paras.orgUuid &&
					(paras.orgUuid =
						this.areaSwiperOrgUuid ||
						(this.$storage.get(this.$rp.common.USER).user.org.benji ?
							this.$storage.get(this.$rp.common.USER).user.org.parentOrgUuid :
							this.$storage.get(this.$rp.common.USER).user.org.orgUuid));
				// 来源地查看全省数据(取消)
				// !chIdx && (paras.orgUuid = this.userInfo.provOrgUuid);
				this.$u.loading('数据加载中...');
				internalService[!chIdx ? 'selectTrueCaseSourceList' : 'selectTrueCaseSourceOutList'](1, 1000, paras).then((dr) => {
					this.$u.hideLoading();
					if (dr.success) {
						this.swiperCfg[this.hIndex].dataSource = dr.data;
					} else {
						this.$u.error(dr.msg);
					}
				});
			},

			// 点击查获 被查获（idx对应label数组的下标）
			handleTapHeader(idx) {
				// 重置区划
				this.areaSwiperOrgUuid = '';
				// 记录当前是查获或被查获
				this.chFlag = idx;
				// 底部菜单来源地改为去向地
				this.list[2].text = idx ? '去向地' : '来源地';
				this.formData.cigaOutFlowType = !idx ? '01' : '02';
				this.lodingQy(idx);
			},
			onClick(value) {
				this.formData.cigTime = value;
				if (this.formData.cigTime == 0) {
					this.formData.dateStart = this.formData.newYearStart;
				} else if (this.formData.cigTime == 1) {
					this.formData.dateStart = this.formData.newMonthStart;
				}
			},
			// 单位
			changeUnit(item) {
				this.formData.cigaUnit = item.value;
				this.unitName = item.text;
			},
			// 点击列表项,记录点击的专卖局
			handleClickRow(item, kCode) {
				this.searchParam[kCode] = item[kCode];
				this.areaSwiperOrgUuid = this.searchParam.orgUuid;
				this.showCity = item.bizOrgLevel;
			},
			// 刷新
			handlerReload() {
				// 刷新时重置页面及部分参数
				this.hIndex = this.chFlag;
				// this.areaSwiperOrgUuid = "";
				// this.previewOrgUuid = "";
				// let nowUnit = this.formData.cigaUnit
				// this.searchParam = {};
				// this.resetSearchParam();
				// this.formData.cigaUnit = nowUnit
				// this.showCity = '';
				// this.chFlag = 0;
				this.handleChangeTab(this.tabIndex);
			},
			// 显示查询条件
			handlerShowSearch() {
				this.showSearch = !this.showSearch;
			},
			// tab切换
			handleChangeTab(index) {
				if (index == 0) {
					// 区域
					this.handleResetTitle('真烟流动');
					this.tabIndex = index;
					this.showCity = '';
					// 点击区域时默认按第一屏展示
					this.areaSwiperIdx = 0;
					this.lodingQy(this.chFlag);
				} else {
					// if (this.chFlag && !this.areaSwiperOrgUuid) {
					//   this.$modal.alert("请先选择地区或区县");
					//   return false;
					// }
					this.tabIndex = index;
					if (index == 1) {
						// 品规
						this.handleResetTitle(['查获品规', '被查获品规', ][this.chFlag]);
						if (this.chFlag == 1) {
							if (this.orgLevel == '1') {
								// 区分省 市 县级
								if (this.showCity == '3') {
									this.swiperCfg[2].headers = this.resetHeader(Headers.brand2); // 县
								} else if (this.showCity == '2') {
									this.swiperCfg[2].headers = this.resetHeader(Headers.brand0); // 市
								} else {
									this.swiperCfg[2].headers = this.resetHeader(Headers.brand1); // 省
								}
							} else if (this.orgLevel == '2') {
								if (this.showCity == '3') {
									this.swiperCfg[2].headers = this.resetHeader(Headers.brand2); // 县
								} else {
									this.swiperCfg[2].headers = this.resetHeader(Headers.brand0); // 市
								}
							} else {
								this.swiperCfg[2].headers = this.resetHeader(Headers.brand2); // 县
							}
						} else if (this.chFlag == 0) {
							this.swiperCfg[2].headers = this.resetHeader(Headers.brand); // 查获
						}
						this.lodingBrand(this.chFlag);
					} else {
						this.handleResetTitle(this.list[index].text); // 来源地或去向地
						this.lodingSource(this.chFlag);
					}
				}
				return true;
			},
			resetHeader(hs) {
				let hds = this.$u.deepClone(hs);
				hds.forEach((arr) => {
					arr[0].label = ['查获', '被查获', ][this.chFlag] + arr[0].label;
				});
				return hds;
			},
			// 查询
			handleSearch() {
				this.showSearch = false;
				this.handleChangeTab(this.tabIndex);
			},
			// 重置
			resetSearchParam() {
				this.formData = this.$u.deepClone(this.cloneFormData);
				this.unitName = '万支';
			},
			// 查看区域详情
			handlePreview(orgItem) {
				debugger;
				this.previewOrgUuid = orgItem.orgUuid;
				this.areaSwiperOrgUuid = orgItem.orgUuid;
				this.lodingQy(this.hIndex);
			},
			fabtrigger(act) {
				if (act.index === 0) {
					this.handlerReload();
				} else if (act.index === 1) {
					this.handlerShowSearch();
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	@import '@/style/common/rightMenu.scss';

	.end {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		z-index: 999;
	}

	.notes {
		color: red;
		padding: 20rpx 20rpx;
		// padding-top: 85rpx;
	}

	.tagsize {
		height: 24px;
		width: 55px;
		text-align: center;
	}
</style>
